package com.fengye.algorithms.leecode;

import com.fengye.algorithms.leecode.common.ListNode;

/**
 * @Author fengye
 * @Date 2023/4/8 11:47
 **/
public class RemoveElements203 {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null) {
            return head;
        }

        ListNode prev = head;
        if(prev.val == val) {
            ListNode next = prev.next;
            while (next != null && next.val == val) {
                prev = next;
                next = next.next;
            }
            head = next;
            prev.next = null;// for gc
            if(next == null) {
                return null;
            }
        }

        ListNode pos = head;
        ListNode next = pos.next;
        while (next != null) {
            if(next.val == val) {
                pos.next = next.next;
                next.next = null;// for gc
                next = pos.next;
            } else {
                pos = pos.next;
                next = next.next;
            }
        }

        return head;
    }
}
